﻿using LightSO.Entity;
using LightSO.ILibrary;
using MongoDB.Bson;
using Spring.Context.Support;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;

namespace LightSO.Extensions
{
    public static class SpringExtension
    {
        /// <summary>
        /// 获取数据仓储(SQL)
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="entity">数据实体</param>
        /// <returns>数据仓储</returns>
        public static IRepository<T> Repo<T>(this T entity) where T : LightSO.Entity.EntityBase, new()
        {
            return Ioc<IRepository<T>>();
        }

        /// <summary>
        /// 获取数据仓储(MongoDb)
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <returns>数据仓储</returns>
        public static IMongoRepository<T> RepoMongo<T>() where T : LightSO.Entity.EntityBase, new()
        {
            return Ioc<IMongoRepository<T>>();
        }

        /// <summary>
        /// 获取数据仓储(Redis)
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <returns>数据仓储</returns>
        public static IRedisRepository<T> RepoRedis<T>() where T : LightSO.Entity.EntityBase, new()
        {
            return Ioc<IRedisRepository<T>>();
        }

        /// <summary>
        /// 注入接口
        /// </summary>
        /// <typeparam name="T">接口类型</typeparam>
        /// <returns>注入到接口的对象</returns>
        public static T Ioc<T>() where T : InterfaceBase
        {
            var name = typeof(T).Name.Split(new string[] { "`" }, StringSplitOptions.RemoveEmptyEntries)[0];
            if (typeof(T).Name == "IRepository`1" ||
                typeof(T).Name == "IMongoRepository`1" ||
                typeof(T).Name == "IRedisRepository`1")
            {
                var factory = (ILibraryFactory)ContextRegistry.GetContext().GetObject(name);
                if (ContextRegistry.GetContext().IsSingleton(name))
                    return factory.Single<T>();
                else
                    return factory.Create<T>();
            }
            if (typeof(T).Name.Length > 2 &&
                typeof(T).Name.Substring(0, 1) == "I" &&
                Regex.IsMatch(typeof(T).Name.Substring(1, 1), "[A-Z]"))
            {
                return (T)ContextRegistry.GetContext().GetObject(typeof(T).Name.Substring(1));
            }

            return (T)ContextRegistry.GetContext().GetObject(name);
        }
    }
}
